package com.ysx.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysx.comment.dto.CommentRelyDto;
import com.ysx.comment.dto.CommentReplyLikeDto;
import com.ysx.comment.dto.CommentReplySaveDto;
import com.ysx.comment.ducument.ApCommentDocument;
import com.ysx.comment.ducument.ApCommentReplyDocument;
import com.ysx.comment.ducument.ApCommentReplyLikeDocument;
import com.ysx.comment.mapper.ApCommentReplyMapper;
import com.ysx.comment.pojo.ApCommentReply;
import com.ysx.comment.service.ApCommentReplyService;
import com.ysx.comment.vo.CommentReplyVo;
import com.ysx.common.pojo.StatusCode;
import com.ysx.common.utils.RequestHeaderInfoUtils;
import com.ysx.exception.ToutiaoException;
import com.ysx.user.feign.ApUserFeign;
import com.ysx.user.pojo.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * APP评论回复信息表 服务实现类
 * </p>
 *
 * @author ljh
 * @since 2021-10-08
 */
@Service
public class ApCommentReplyServiceImpl extends ServiceImpl<ApCommentReplyMapper, ApCommentReply> implements ApCommentReplyService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ApUserFeign apUserFeign;


    /**
     * 加载回复的评论
     * @param commentRelyDto
     * @return
     */
    @Override
    public List<CommentReplyVo> loadPage(CommentRelyDto commentRelyDto) {
        //1查询评论列表
        // select * from reply where creattime < ? and commentId=? order by createtime desc limit 10
        LocalDateTime minDate = commentRelyDto.getMinDate();

        //一页最后一条记录的时间 作为查询条件
        if(minDate==null){
            minDate=LocalDateTime.now();
        }


        Query query = Query.query(
                Criteria.where("commentId").is(commentRelyDto.getCommentId())
                        .and("createdTime").lt(minDate)
        );

        //排序
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));

        //限制（分页） 10条记录
        query.limit(10);

        List<ApCommentReplyDocument> replyDocumentList = mongoTemplate.find(query, ApCommentReplyDocument.class);

        //找 当前用户点站了哪些回复
        //2查询当前用户对应的点赞记录 select * from relylike where userId=? and replyId in (回复列表中的 回复ID)
        List<String> ids = replyDocumentList.stream().map(reply -> reply.getId()).collect(Collectors.toList());




        List<ApCommentReplyLikeDocument> replyLikeDocumentList = null;
        String userInfo = RequestHeaderInfoUtils.getHeaderUserId();
        if(!userInfo.equals("0")){//真实的用户才能点赞的，所以只查询真实用户的点赞记录
            Query query1 = Query.query(
                    Criteria.where("userId").is(Integer.valueOf(userInfo))
                            .and("commentReplyId").in(ids)
            );
            //一定是张三点赞了的
            replyLikeDocumentList = mongoTemplate.find(query1, ApCommentReplyLikeDocument.class);
        }


        //3组合 设置标记是否被点赞   返回voList
        List<CommentReplyVo> commentReplyVoList =new ArrayList<CommentReplyVo>();

        //目前该数据没有被标记 当前用户是否点赞了该回复
        commentReplyVoList = JSON.parseArray(JSON.toJSONString(replyDocumentList), CommentReplyVo.class);

        if(replyLikeDocumentList!=null) {
            for (CommentReplyVo commentReplyVo : commentReplyVoList) {

                for (ApCommentReplyLikeDocument replyLikeDocument : replyLikeDocumentList) {
                    if (replyLikeDocument.getCommentReplyId().equals(commentReplyVo.getId())) {
                        commentReplyVo.setOperation(1);//匹配上 就是点赞了
                    }
                }
            }
        }
        return commentReplyVoList;
    }


    /**
     * 回复评论
     * @param commentReplySaveDto
     */
    @Override
    public void saveReply(CommentReplySaveDto commentReplySaveDto)throws Exception {
        //1.校验数据是否符合要求
        if(StringUtils.isEmpty(commentReplySaveDto.getContent()) || commentReplySaveDto.getCommentId()==null){
            throw new ToutiaoException("回复的内容不能为空，评论ID也不能为空");
        }
        //2.判断当前用户是否已经登录
        String userInfo = RequestHeaderInfoUtils.getHeaderUserId();
        if(userInfo.equals("0")){
            throw new ToutiaoException(StatusCode.NEED_LOGIN.code(),StatusCode.NEED_LOGIN.message());
        }
        //3.设置数据 添加到 mongo中
        ApCommentReplyDocument entity = new ApCommentReplyDocument();
        entity.setLikes(0);
        entity.setContent(commentReplySaveDto.getContent());
        entity.setCommentId(commentReplySaveDto.getCommentId());
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setCreatedTime(LocalDateTime.now());

        //指的是写下回复的用户的ID 也就是当前登录用户的ID
        entity.setUserId(Integer.valueOf(userInfo));

        //远程调用  性能      token创建的时候 多添加两个字段  然后网关校验

        //校验之后 将令牌解析出来 解析出 用户的ID 用户的名称 用户的头像
        ApUser apUser = apUserFeign.findById(Integer.valueOf(userInfo)).getData();
        if(apUser!=null){
            entity.setNickName(apUser.getName());
            entity.setHeadImage(apUser.getImage());
        }

        mongoTemplate.insert(entity);

        //要将该回复对应的评论的回复数量+1  todo
        //update xxx set replys=replys+1 where id=? (评论表)

        Query query2 = Query.query(Criteria.where("_id").is(commentReplySaveDto.getCommentId()));
        Update update = new Update();
        update.inc("replys");//+1 评论的回复数量 + 1
        mongoTemplate.findAndModify(query2,update, ApCommentDocument.class);
    }


    /**
     * 回复评论点赞
     * @param commentReplyLikeDto
     */
    @Override
    public void replyLike(CommentReplyLikeDto commentReplyLikeDto) throws Exception{
        //1.校验数据是否符合要求
        if(StringUtils.isEmpty(commentReplyLikeDto.getCommentReplyId()) || commentReplyLikeDto.getOperation()==null){
            throw new ToutiaoException("点赞的评论的ID 和操作类型不能为null");
        }
        if(commentReplyLikeDto.getOperation()>1 || commentReplyLikeDto.getOperation()<0){
            throw new ToutiaoException("operation操作范围只能是0-1");
        }
        //2.判断当前用户是否已经登录
        String userInfo = RequestHeaderInfoUtils.getHeaderUserId();
        if(userInfo.equals("0")){
            throw new ToutiaoException(StatusCode.NEED_LOGIN.code(),StatusCode.NEED_LOGIN.message());
        }
        //3.设置数据 添加点赞记录,删除点赞记录到 mongo中
        if(commentReplyLikeDto.getOperation()==1){

            //条件判断 如果有点赞了就不用再点赞了
            Query query2 = Query.query(Criteria.where("userId")
                    .is(Integer.valueOf(userInfo))
                    .and("commentReplyId").is(commentReplyLikeDto.getCommentReplyId()));
            List<ApCommentReplyLikeDocument> likesList = mongoTemplate.find(query2, ApCommentReplyLikeDocument.class);
            if(likesList!=null && likesList.size()>0){
                return;
            }

            ApCommentReplyLikeDocument entity = new ApCommentReplyLikeDocument();
            entity.setUserId(Integer.valueOf(userInfo));
            entity.setCommentReplyId(commentReplyLikeDto.getCommentReplyId());
            mongoTemplate.save(entity);

            //评论的数量+1   select * from comment where id=?  update
            /*ApCommentDocument apCommentDocument = mongoTemplate.findById(commentLikeDto.getCommentId(), ApCommentDocument.class);
            apCommentDocument.setLikes(apCommentDocument.getLikes()+1);
            mongoTemplate.save(apCommentDocument);*/

            Query query = Query.query(Criteria.where("_id").is(commentReplyLikeDto.getCommentReplyId()));
            Update update = new Update();
            update.inc("likes");//+1 回复的点赞数量+1
            mongoTemplate.findAndModify(query,update, ApCommentReplyDocument.class);

        }else{
            //取消点赞 delete from xxx where user_id=? and commentId=?
            Query query = Query.query(Criteria.where("userId").is(Integer.valueOf(userInfo)).and("commentReplyId").is(commentReplyLikeDto.getCommentReplyId()));
            List<ApCommentReplyLikeDocument> allAndRemove = mongoTemplate.findAllAndRemove(query, ApCommentReplyLikeDocument.class);
            //如果点赞记录不存在 那么就直接返回
            if (allAndRemove == null) {
                return;
            }

            //回复的点赞数 -1
            Query query1 = Query.query(Criteria.where("_id").is(commentReplyLikeDto.getCommentReplyId()));
            Update update = new Update();
            update.inc("likes",-1);//-1
            mongoTemplate.findAndModify(query1,update,ApCommentReplyDocument.class);
        }
    }



}
